# -*- coding : utf_8 -*-
'''
=======================================
Time : 2025/3/23 0:27
Author : 田霄汉
Email : 522989570@qq.com
File : log_util.py
Project : pytest_demo
=======================================
'''

import logging
import os
import time
from config.setting import file_path
from logging.handlers import RotatingFileHandler  # 按文件大小滚动备份
from colorlog import ColoredFormatter  # 设置不同级别颜色

# 取setting.py文件中的logs目录
logs_path = file_path['log']
# 不存在logs目录就创建
if not os.path.exists(logs_path):
    os.mkdir(logs_path)
# log文件命名规则
logfile_name = logs_path + r'\test{}.log'.format(time.strftime('%Y%m%d'))


class LogUtil:

    @classmethod
    def setting_log_color(cls):
        log_color_config = {
            'DEBUG': 'cyan',
            'INFO': 'green',
            'WARNING': 'yellow',
            'ERROR': 'red',
            'CRITICAL': 'purple'
        }
        formatter = ColoredFormatter(
            '%(log_color)s %(levelname)s-%(asctime)s-%(filename)s:%(lineno)d-%(funcName)s-%(message)s',
            log_colors=log_color_config)
        return formatter

    @classmethod
    def output_logs(cls):
        logger = logging.getLogger(__name__)
        steam_format = cls.setting_log_color()
        # 防止重复打印日志
        if not logger.handlers:
            logger.setLevel(logging.DEBUG)
            log_format = logging.Formatter(
                '%(levelname)s-%(asctime)s-%(filename)s:%(lineno)d-%(funcName)s-%(message)s')
            # 日志输出到控制台
            console_output = logging.StreamHandler()
            # 设置日志级别(DEBUG以上级别打印出来)
            console_output.setLevel(logging.DEBUG)
            # 设置日志格式
            console_output.setFormatter(steam_format)
            # 打印到控制台增加到logger.Hangdler()
            logger.addHandler(console_output)

            # 日志输出到*.log文件中
            # 滚动输出到*.log文件中
            file_output = RotatingFileHandler(filename=logfile_name,
                                              mode='a',
                                              maxBytes=5242880,
                                              backupCount=7,
                                              encoding='utf-8')
            file_output.setLevel(logging.DEBUG)
            file_output.setFormatter(log_format)
            logger.addHandler(file_output)

        return logger


logutil = LogUtil()
logs = logutil.output_logs()